package top.tangyh.lamp.care.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.tangyh.basic.cache.redis2.RedisOps;
import top.tangyh.lamp.base.entity.user.BaseOrg;
import top.tangyh.lamp.base.mapper.user.BaseOrgMapper;
import top.tangyh.lamp.care.entity.*;
import top.tangyh.lamp.care.manager.BDevBindManager;
import top.tangyh.lamp.care.mapper.*;
import top.tangyh.lamp.care.service.BCarePgVteService;
import top.tangyh.lamp.care.service.BDevBindService;
import top.tangyh.lamp.care.service.BPatientService;
import top.tangyh.basic.base.service.impl.SuperServiceImpl;
import top.tangyh.lamp.care.manager.BPatientManager;
import top.tangyh.lamp.care.vo.query.PatientBindInputVO;
import top.tangyh.lamp.care.vo.query.PatientHomePageQueryVO;
import top.tangyh.lamp.care.vo.result.*;
import top.tangyh.lamp.care.vo.save.BPatientSaveVO;
import top.tangyh.lamp.care.vo.save.ObvInfoInVO;
import top.tangyh.lamp.care.vo.save.PatientOtherInfoInVO;
import top.tangyh.lamp.care.vo.update.BPatientUpdateVO;
import top.tangyh.lamp.care.vo.update.RyInfoInVO;
import top.tangyh.lamp.common.constant.EventEnum;
import top.tangyh.lamp.common.constant.YzTypeEnum;
import top.tangyh.lamp.common.properties.SystemProperties;
import top.tangyh.lamp.common.utils.PDateUtils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static top.tangyh.lamp.common.constant.CommonConstant.BIND_EQU_PATIENT;

/**
 * <p>
 * 业务实现类
 * 病人信息表
 * </p>
 *
 * @author zqb
 * @date 2024-07-12 16:37:12
 * @create [2024-07-12 16:37:12] [zqb] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(readOnly = true)
public class BPatientServiceImpl extends SuperServiceImpl<BPatientManager, Long, BPatient> implements BPatientService {

    private final BPatientMapper bPatientMapper;


    private final BaseOrgMapper baseOrgMapper;
    @Autowired
    protected SystemProperties systemProperties;

    private final BCarePgVteService bCarePgVteService;

    private final BInpatientDiagnosisMapper bInpatientDiagnosisMapper;


    private final BHl7YzMapper bHl7YzMapper;

    private final BHl7RkDetailMapper bHl7RkDetailMapper;



    private final BHl7MoveDetailMapper bHl7MoveDetailMapper;

    private final BHl7RyDetailMapper bHl7RyDetailMapper;

    private final BHl7EventMapper bHl7EventMapper;

    private final RedisOps redisOps;


    private final BDevBindMapper bDevBindMapper;



    private final BHl7ObvResultMapper bHl7ObvResultMapper;

    private final BDevBindService bindService;
    private final LeavePatientsMapper leavePatientsMapper;

    @Override
    public List<PatientInfoOutVO> selectListByQuery() {
        List<PatientInfoOutVO> patientInfoList = bPatientMapper.selectPatientListOfSystemLeftMenu(systemProperties.getIcuCode());
        List<String> hospitalNumners = patientInfoList.stream().map(PatientInfoOutVO::getHospitalNumber).collect(Collectors.toList());

//        病区map
        List<BaseOrg> list = baseOrgMapper.selectAllDeptList();
        Map<Long, String> deptMap = list.stream().filter(deptPo -> StrUtil.isNotBlank(deptPo.getName())).collect(Collectors.toMap(BaseOrg::getId, BaseOrg::getName));


        //病人识别号集合
        List<String> patientIdentList = patientInfoList.stream().map(PatientInfoOutVO::getPatientIdent).collect(Collectors.toList());
        //过敏史 patIdent--GmVO 根据识别号
//        Map<String, List<GmOutVO>> gmVoMap = bHl7GmMapper.selectGmListByPatientIdentList(patientIdentList).stream().map(GmOutVO::new).collect(Collectors.groupingBy(GmOutVO::getPatientIdent));

        //观察值 身高 体重 体温 血型 分组后取最新一条观察值 根据识别号 patIdent--obvResultPO
//        Map<String, BHl7ObvResult> obvMap = bHl7ObvResultMapper.selectHl7ObvResultListByPatIdentList(patientIdentList).parallelStream()
//                .collect(Collectors.toMap(BHl7ObvResult::getPatientIdent, Function.identity(), (obv1, obv2) -> obv1.getObvTime().isAfter(obv2.getObvTime()) ? obv1 : obv2));

        //组合各类信息到vo
//        Map<String, List<PatientBedHisVO>> finalBedMap = bedMap;
//        Map<String, List<PatientNameHisVO>> finalNameMap = nameMap;
//        Map<String, List<PatientWardHisVO>> finalWardMap = wardMap;
        List<String> listOfHospitalNumber = patientInfoList.stream().map(PatientInfoOutVO::getHospitalNumber).collect(Collectors.toList());
        List<BInpatientDiagnosis> inpatientDiagnosisPOSAll = bInpatientDiagnosisMapper.selectListByHospitalAll(listOfHospitalNumber);

//        List<OperaInfoOutVO> operaInfoOutVOListAll = bHl7YzMapper.selectListByHospitalNumbersAndType(listOfHospitalNumber, YzTypeEnum.SHOUSHU.getTypeCode()).stream().map(OperaInfoOutVO::new).collect(Collectors.toList());

       // List<MoveInfoOutVO> moveInfoOutVOListAll = bHl7MoveDetailMapper.selectListByHospitalNumbers(listOfHospitalNumber).stream().map(MoveInfoOutVO::new).collect(Collectors.toList());
        List<BHl7RkDetail> yxHl7RkDetailPOListAll = bHl7RkDetailMapper.selectRkListOfTopNewTime(listOfHospitalNumber);

        List<BHl7RyDetail> yxHl7RyDetailPOListAll = bHl7RyDetailMapper.selectRyListOfTopNewTime(listOfHospitalNumber);
//        List<BHl7Event> listCkAll = bHl7EventMapper.selectEventListOfTopNewTime(listOfHospitalNumber, EventEnum.CK.getEventType());

        List<BHl7Event> listRkAll = bHl7EventMapper.selectEventListOfTopNewTime(listOfHospitalNumber, EventEnum.RK.getEventType());

//        List<BHl7YzYaoExe> yaoExePOSListAll = bHl7YzYaoExeMapper.selectListByTimeHospitalNumbers(listOfHospitalNumber);
        patientInfoList.forEach(patientInfoOutVO -> {
            String hospitalNumber = patientInfoOutVO.getHospitalNumber();
            String patientIdent = patientInfoOutVO.getPatientIdent();


            //        病区
            if (StrUtil.isNotBlank(patientInfoOutVO.getWardIdent())) {
                patientInfoOutVO.setWardName(deptMap.get(patientInfoOutVO.getWardIdent()));
            }
            //        先判断住院号是否为空
            if (StrUtil.isNotBlank(hospitalNumber)) {


                List<RkZdInfoOutVO> rkZdInfoOutVOList = new ArrayList<>();
                //初   步西医主诊
                List<BInpatientDiagnosis> inpatientDiagnosisPOS = inpatientDiagnosisPOSAll.stream().filter(e -> e.getHospitalNumber().equals(hospitalNumber) && e.getDiagnosisType() == 141).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(inpatientDiagnosisPOS)) {
                    RkZdInfoOutVO rkZdInfoOutVO = new RkZdInfoOutVO();
                    rkZdInfoOutVO.setZdName(inpatientDiagnosisPOS.get(0).getDiagnosisContent());
                    rkZdInfoOutVO.setId(inpatientDiagnosisPOS.get(0).getId());
                    rkZdInfoOutVOList.add(rkZdInfoOutVO);
                    if (null == patientInfoOutVO.getDiagnosisId()) {
                        patientInfoOutVO.setDiagnosisId(inpatientDiagnosisPOS.get(0).getId());
                    }
                } else {
                    List<BInpatientDiagnosis> inpatientDiagnosisPOS130 = inpatientDiagnosisPOSAll.stream().filter(e -> e.getHospitalNumber().equals(hospitalNumber) && e.getDiagnosisType() == 130).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(inpatientDiagnosisPOS130)) {
                        RkZdInfoOutVO rkZdInfoOutVO = new RkZdInfoOutVO();
                        rkZdInfoOutVO.setZdName(inpatientDiagnosisPOS130.get(0).getDiagnosisContent());
                        rkZdInfoOutVO.setId(inpatientDiagnosisPOS130.get(0).getId());
                        rkZdInfoOutVOList.add(rkZdInfoOutVO);
                        if (null == patientInfoOutVO.getDiagnosisId()) {
                            patientInfoOutVO.setDiagnosisId(inpatientDiagnosisPOS130.get(0).getId());
                        }
                    }
                }
                patientInfoOutVO.setRkZdInfoList(rkZdInfoOutVOList);
                Map<String, List<BInpatientDiagnosis>> allmap = inpatientDiagnosisPOSAll.stream().
                        filter(e -> e.getHospitalNumber().equals(hospitalNumber)).sorted(Comparator.comparing(BInpatientDiagnosis::getDiagnosisTime).reversed()).collect(Collectors.groupingBy(v -> v.getHospitalNumber()
                                + String.valueOf(v.getDiagnosisType()) + v.getDiagnosisDoctorName()));
                List<BInpatientDiagnosis> inpatientDiagnosisAllPOS = allmap.values().stream().map(v -> v.get(0)).collect(Collectors.toList());
                patientInfoOutVO.setRkZdList(inpatientDiagnosisAllPOS);


                //入院信息 时间 护理等级 主治医生 住院次数 根据住院号
                BHl7RyDetail yxHl7RyDetailPO = new BHl7RyDetail();
                List<BHl7RyDetail> yxHl7RyDetailPOList = yxHl7RyDetailPOListAll.stream().filter(e -> e.getHospitalNumber().equals(hospitalNumber)).collect(Collectors.toList());

                if (null != yxHl7RyDetailPOList && yxHl7RyDetailPOList.size() > 0) {
                    yxHl7RyDetailPO = yxHl7RyDetailPOList.get(0);
                }


                if (yxHl7RyDetailPO != null) {
                    RyInfoOutVO ryInfoOutVO = new RyInfoOutVO();
                    ryInfoOutVO.setId(yxHl7RyDetailPO.getId());
                    ryInfoOutVO.setRyDate(yxHl7RyDetailPO.getRyTime());
                    ryInfoOutVO.setZycs(yxHl7RyDetailPO.getZycs());
                    ryInfoOutVO.setSzDoctorName(yxHl7RyDetailPO.getSzDoctorName());
                    patientInfoOutVO.setRyInfo(ryInfoOutVO);
                }


                //查找入科消息 得到入科时间
                BHl7Event yxHl7EventPO = new BHl7Event();
                List<BHl7Event> eventRkPOList = listRkAll.stream().filter(e -> e.getHospitalNumber().equals(hospitalNumber)).collect(Collectors.toList());
                if (null != eventRkPOList && eventRkPOList.size() > 0) {
                    yxHl7EventPO = eventRkPOList.get(0);
                }
                if (yxHl7EventPO != null) {
                    //入科信息
                    RkInfoOutVO rkInfoOutVO = new RkInfoOutVO();
                    LocalDateTime rkDate = yxHl7EventPO.getEventTime();
                    rkInfoOutVO.setId(yxHl7EventPO.getId());
                    rkInfoOutVO.setRkDate(patientInfoOutVO.getRkTimeReal());
                    patientInfoOutVO.setRkInfo(rkInfoOutVO);
                    //入科前用药 入重症科室前的所有执行用药 根据住院号
//                    List<BHl7YzYaoExe> yzYaoExePOList = yaoExePOSListAll.stream().filter(e -> e.getHospitalNumber().equals(hospitalNumber)).collect(Collectors.toList());
//                    yzYaoExePOList = yzYaoExePOList.stream().filter(e -> e.getStartTime().isBefore(rkDate)).collect(Collectors.toList());
//                    List<RkYongYaoOutVO> rkYongYaoOutVOList = yzYaoExePOList.stream().map(RkYongYaoOutVO::new).collect(Collectors.toList());
//
//                    patientInfoOutVO.setRkYongYaoInfo(rkYongYaoOutVOList);
                    //查找主治医生
                    BHl7RkDetail rkDetailPO = new BHl7RkDetail();
                    List<BHl7RkDetail> yxHl7RkDetailPOList = yxHl7RkDetailPOListAll.stream().filter(e -> e.getHospitalNumber().equals(hospitalNumber)).collect(Collectors.toList());
                    if (null != yxHl7RkDetailPOList && yxHl7RkDetailPOList.size() > 0) {
                        rkDetailPO = yxHl7RkDetailPOList.get(0);
                    }

                    if (rkDetailPO != null) {
                        rkInfoOutVO.setZzDoctorIdent(rkDetailPO.getZzDoctorIdent());
                        rkInfoOutVO.setZzDoctorName(rkDetailPO.getZzDoctorName());
                    }
                }

                //从医嘱获取取手术时间和名称 根据住院号

//                List<OperaInfoOutVO> operaInfoOutVOList = operaInfoOutVOListAll.stream().filter(e -> e.getHospitalNumber().equals(hospitalNumber)).collect(Collectors.toList());
//                patientInfoOutVO.setOperaInfo(operaInfoOutVOList);

                //转科记录 根据住院号

//                List<MoveInfoOutVO> moveInfoOutVOList = moveInfoOutVOListAll.stream().filter(e -> e.getHospitalNumber().equals(hospitalNumber)).collect(Collectors.toList());
//                patientInfoOutVO.setMoveInfo(moveInfoOutVOList);

                //过敏史
//                if (gmVoMap.containsKey(patientIdent)) {
//                    patientInfoOutVO.setGmList(gmVoMap.get(patientIdent));
//                }
                //观测值
//                if (obvMap.containsKey(patientIdent)) {
//                    BHl7ObvResult obvResultPO = obvMap.get(patientIdent);
//                    ObvInfoOutVO obvInfoOutVO = new ObvInfoOutVO();
//                    obvInfoOutVO.setId(obvResultPO.getId());
//                    obvInfoOutVO.setHeight(obvResultPO.getHeight());
//                    obvInfoOutVO.setWeight(obvResultPO.getWeight());
//                    obvInfoOutVO.setTemp(obvResultPO.getTemp());
//                    patientInfoOutVO.setObvInfoOutVO(obvInfoOutVO);
//                }
//                // 查询特殊事件
//                BHl7Event CKEvent = new BHl7Event();
//                List<BHl7Event> eventPOList = listCkAll.stream().filter(e -> e.getHospitalNumber().equals(hospitalNumber)).collect(Collectors.toList());
//                if (null != eventPOList && eventPOList.size() > 0) {
//                    CKEvent = eventPOList.get(0);
//                }

//                if (CKEvent != null) {
//                    patientInfoOutVO.setEventTime(CKEvent.getEventTime());
//                }
//                patientInfoOutVO.setBedList(finalBedMap.get(hospitalNumber));
//                patientInfoOutVO.setNameList(finalNameMap.get(hospitalNumber));
//                patientInfoOutVO.setWardList(finalWardMap.get(hospitalNumber));
            }
        });
        return patientInfoList;
    }

    @Override
    public List<PatientInfoOutVO> selectListByQueryNew() {

        return null;
    }

    @Override
    public List<PatientBedInfoOutVO> selectListBedByQuery() {
        List<PatientBedInfoOutVO> patientInfoList = bPatientMapper.selectPatientListOfSystemLeftMenuBed(systemProperties.getIcuCode(), null);
        return patientInfoList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePatBaseInfo(PatBaseInfoInVO baseInfoVO) {
        BPatient patientPO = new BPatient();
        patientPO.setId(baseInfoVO.getId());
        patientPO.setContacts(baseInfoVO.getContacts());
        patientPO.setContactsPhone(baseInfoVO.getContactsPhone());
        patientPO.setRelation(baseInfoVO.getRelation());
        patientPO.setAddress(baseInfoVO.getAddress());
        patientPO.setBloodType(baseInfoVO.getBloodType());
        patientPO.setAge(baseInfoVO.getAge());
        patientPO.setNursingLevel(baseInfoVO.getNursingLevel());
        bPatientMapper.updateById(patientPO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePatOtherInfo(PatientOtherInfoInVO lcInfoVO) {
        // 处理护理等级 主治医生 入院明细更改
        RyInfoInVO ryInfo = lcInfoVO.getRyInfo();
        if (ryInfo != null) {
            BHl7RyDetail yxHl7RyDetailPO = new BHl7RyDetail();
            if (ryInfo.getRyTime() != null) {
                yxHl7RyDetailPO.setRyTime(PDateUtils.getDateTimeOfTimestamp(ryInfo.getRyTime()));
            }
            if (ryInfo.getId() != null) {
                yxHl7RyDetailPO.setId(ryInfo.getId());
                bHl7RyDetailMapper.updateById(yxHl7RyDetailPO);
            } else {
                yxHl7RyDetailPO.setPatientIdent(lcInfoVO.getPatientIdent());
                yxHl7RyDetailPO.setHospitalNumber(lcInfoVO.getHospitalNumber());
                bHl7RyDetailMapper.insert(yxHl7RyDetailPO);
            }
        }

        //处理体征
        ObvInfoInVO obvInfoInVO = lcInfoVO.getObvInfo();
        if (obvInfoInVO != null) {
            BHl7ObvResult obvResultPO = new BHl7ObvResult();
            obvResultPO.setHeight(obvInfoInVO.getHeight());
            obvResultPO.setWeight(obvInfoInVO.getWeight());
            String temp = obvInfoInVO.getTemp();
            if (StrUtil.isNotBlank(temp)) {
                obvResultPO.setTemp(Double.parseDouble(temp));
            }
            if (obvInfoInVO.getId() != null) {
                obvResultPO.setId(obvInfoInVO.getId());
                bHl7ObvResultMapper.updateById(obvResultPO);
            } else {
                obvResultPO.setPatientIdent(lcInfoVO.getPatientIdent());
                obvResultPO.setHospitalNumber(lcInfoVO.getHospitalNumber());
                obvResultPO.setObvTime(LocalDateTime.now());
                bHl7ObvResultMapper.insert(obvResultPO);
            }
        }
        // 入科信息更改
        top.tangyh.lamp.care.vo.save.RkInfoInVO rkInfo = lcInfoVO.getRkInfo();
        if (rkInfo != null) {
            BHl7Event eventPO = new BHl7Event();
            if (rkInfo.getRkTime() != null) {
                eventPO.setEventTime(PDateUtils.getDateTimeOfTimestamp(rkInfo.getRkTime()));
            }
            if (rkInfo.getId() != null) {
                eventPO.setId(rkInfo.getId());
                bHl7EventMapper.updateById(eventPO);
            } else {
                eventPO.setPatientIdent(lcInfoVO.getPatientIdent());
                eventPO.setHospitalNumber(lcInfoVO.getHospitalNumber());
                eventPO.setEventType(EventEnum.RK.getEventType());
                bHl7EventMapper.insert(eventPO);
            }
            //更改主治医生信息 入科detail表
            String zzDoctorIdent = rkInfo.getZzDoctorIdent();
            String zzDoctorName = rkInfo.getZzDoctorName();
            if (StrUtil.isAllNotBlank(zzDoctorIdent, zzDoctorName)) {
                BHl7RkDetail rkDetailPO = bHl7RkDetailMapper.selectOneByHospitalNumber(lcInfoVO.getHospitalNumber());
                if (rkDetailPO != null) {
                    rkDetailPO.setZzDoctorIdent(zzDoctorIdent);
                    rkDetailPO.setZzDoctorName(zzDoctorName);
                    bHl7RkDetailMapper.updateById(rkDetailPO);
                } else {
                    BHl7RkDetail newRkDetailPO = new BHl7RkDetail();
                    newRkDetailPO.setPatientIdent(lcInfoVO.getPatientIdent());
                    newRkDetailPO.setHospitalNumber(lcInfoVO.getHospitalNumber());
                    newRkDetailPO.setZzDoctorIdent(zzDoctorIdent);
                    newRkDetailPO.setZzDoctorName(zzDoctorName);
                    newRkDetailPO.setRkTime(LocalDateTime.now());
                    bHl7RkDetailMapper.insert(newRkDetailPO);
                }
            }
        }
        //处理出科特殊事件,并将对应病人的在科状态从1改成0
        if (lcInfoVO.getEventInVO() != null) {
            if (null != lcInfoVO.getEventInVO().getEventTime()) {
                // 增加出科的特殊状态
                BHl7Event yxHl7EventPO = new BHl7Event();
                yxHl7EventPO.setHospitalNumber(lcInfoVO.getHospitalNumber());
                yxHl7EventPO.setPatientIdent(lcInfoVO.getPatientIdent());
                yxHl7EventPO.setWardIdent(lcInfoVO.getWardIdent());
                yxHl7EventPO.setDeptIdent(lcInfoVO.getDeptIdent());
                yxHl7EventPO.setDeptName(systemProperties.getIcuName());
                yxHl7EventPO.setBedNumber(lcInfoVO.getBedNumber());
                // 处理特殊事件的时间和事件名，事件名通过枚举进行比较
                yxHl7EventPO.setEventTime(PDateUtils.getDateTimeOfTimestamp(lcInfoVO.getEventInVO().getEventTime()));
                Integer eventType = EventEnum.CK.getEventType();
                yxHl7EventPO.setEventType(eventType);
                bHl7EventMapper.insert(yxHl7EventPO);

                //修改病人 为离院状态
                int rows = bPatientMapper.updateLiYuanStatus(lcInfoVO.getHospitalNumber(), 1);
                if (rows > 0) {
                    //相应绑定设备数据清空，删除病人和设备的绑定关系
                    //查询该病人是否有设备绑定
                    List<BDevBind> listdevBind = bDevBindMapper.selectListByPatIdent(lcInfoVO.getPatientIdent());
                    if (listdevBind.size() > 0) {
                        for (int i = 0; i < listdevBind.size(); i++) {
                            BDevBind devBindPO = listdevBind.get(i);
                            //删除绑定中间表的数据，根据病人识别号和设备识别号作为条件删除
                            bDevBindMapper.deleteByDevCodePatIdent(devBindPO.getDevCode(), devBindPO.getPatientIdent());

                            //删除redis中绑定关系
                            redisOps.del(BIND_EQU_PATIENT + devBindPO.getDevCode());
                        }

                    }

                }


////            // 将对应病人的在科状态从1改成0
//            yxPatientMapper.updateZaiKeStatus(lcInfoVO.getHospitalNumber());
                // 同时同步病人归转记录里急诊科室记录的出科时间
                if (null != lcInfoVO.getEventInVO().getEventTime()) {
                    bHl7MoveDetailMapper.updateZcTime(systemProperties.getIcuCode(), DateUtil.date(lcInfoVO.getEventInVO().getEventTime()));
                }


                //手动出科病人信息
                LeavePatients leavePatientsPO = new LeavePatients();
                leavePatientsPO.setEventId(yxHl7EventPO.getId());
                leavePatientsPO.setBedNumber(lcInfoVO.getBedNumber());

                //获得时间戳
                // long second = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).getEpochSecond();
                // 将时间戳转为当前时间
                LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(lcInfoVO.getEventInVO().getEventTime() / 1000, 0, ZoneOffset.ofHours(8));
                leavePatientsPO.setCkTime(localDateTime);
                leavePatientsPO.setHospitalNumber(lcInfoVO.getHospitalNumber());
                leavePatientsPO.setPatientIdent(lcInfoVO.getPatientIdent());

                BPatient patientPO = bPatientMapper.selectOneByPatIdent(lcInfoVO.getPatientIdent());
                leavePatientsPO.setPatientName(patientPO.getPatientName());
                leavePatientsPO.setIsCancel(0);
                leavePatientsMapper.insert(leavePatientsPO);
            }







        }
    }

    @Override
    public List<PatientHomePageOutVO> selectPatientsHomePage(PatientHomePageQueryVO queryVO) {

        List<PatientHomePageOutVO> patientInfoList = bPatientMapper.selectListByDeptNew(systemProperties.getIcuCode());


        Set<Long> digids = patientInfoList.stream().filter(v -> null != v.getDiagnosisId()).map(PatientHomePageOutVO::getDiagnosisId).collect(Collectors.toSet());


        List<String> listOfHospitalNumber = patientInfoList.stream().map(PatientHomePageOutVO::getHospitalNumber).collect(Collectors.toList());
        List<String> listOfPatient = patientInfoList.stream().map(PatientHomePageOutVO::getPatientIdent).collect(Collectors.toList());


        if (listOfPatient.size() > 0) {
            Map<String, String> scoreMap = bCarePgVteService.getVteOfTopNewScoreByList(listOfPatient);


            List<BInpatientDiagnosis> inpatientDiagnosisPOSAll141 = bInpatientDiagnosisMapper.selectListByHospitalNumbers(listOfHospitalNumber, 141);
            List<BInpatientDiagnosis> inpatientDiagnosisPOSAll130 = bInpatientDiagnosisMapper.selectListByHospitalNumbers(listOfHospitalNumber, 130);

            Map<String, List<BInpatientDiagnosis>> diagnosisMap141 =
                    inpatientDiagnosisPOSAll141
                            .stream()
                            .collect(Collectors.groupingBy(BInpatientDiagnosis::getHospitalNumber));

            Map<String, List<BInpatientDiagnosis>> diagnosisMap130 =
                    inpatientDiagnosisPOSAll130
                            .stream()
                            .collect(Collectors.groupingBy(BInpatientDiagnosis::getHospitalNumber));
//            List<PatientBindOutputVO> patientBindOutputVO = bindService.queryPatientBindByPatiens(listOfPatient);
//            Map<String, List<PatientBindOutputVO>> mapPatientBindOutputVO =
//                    patientBindOutputVO
//                            .stream()
//                            .collect(Collectors.groupingBy(PatientBindOutputVO::get));


            List<BInpatientDiagnosis> inpatientDiagnosisPOSAllDid = null;
            if (CollectionUtil.isNotEmpty(digids)) {
                inpatientDiagnosisPOSAllDid = bInpatientDiagnosisMapper.selectListByDid(digids);
            }
            if (null == inpatientDiagnosisPOSAllDid) {
                inpatientDiagnosisPOSAllDid = new ArrayList<>();
            }
            Map<Long, List<BInpatientDiagnosis>> didmap = inpatientDiagnosisPOSAllDid.stream().collect(Collectors.groupingBy(BInpatientDiagnosis::getId));
            if (null == didmap) {
                didmap = new HashMap<>();
            }

//            List<PatientBindOutputVO> patientBindOutputVOSAll = yxDevBindMapper.getDevBindByPids(listOfPatient);


            List<BHl7Yz> yxHl7YzPOListll = bHl7YzMapper.selectYzOfTopNewTime(YzTypeEnum.YINSHI.getTypeCode(), listOfHospitalNumber);
            //组合各类信息到vo
            Map<Long, List<BInpatientDiagnosis>> finalDidmap = didmap;
            patientInfoList.forEach(patientInfoOutVO -> {
                String hospitalNumber = patientInfoOutVO.getHospitalNumber();
                String patientIdent = patientInfoOutVO.getPatientIdent();
//
                String score = scoreMap.get(patientIdent);

                patientInfoOutVO.setScore(score);
                //先判断住院号是否为空
                if (StrUtil.isNotBlank(hospitalNumber)) {
                    //入科诊断 根据住院号

                    List<RkZdInfoOutVO> rkZdInfoOutVOList = new ArrayList<>();
                    //初步西医主诊
                    BInpatientDiagnosis select = null;
                    if (null != patientInfoOutVO.getDiagnosisId()) {
                        List<BInpatientDiagnosis> diagnosisPOS = finalDidmap.get(patientInfoOutVO.getDiagnosisId());
                        if (CollectionUtil.isNotEmpty(diagnosisPOS)) {
                            select = diagnosisPOS.get(0);
                        }
                    }
                    if (null == patientInfoOutVO.getDiagnosisId() || null == select) {
                        List<BInpatientDiagnosis> inpatientDiagnosisPOS = diagnosisMap141.get(hospitalNumber);
                        if (CollectionUtil.isNotEmpty(inpatientDiagnosisPOS)) {
                            RkZdInfoOutVO rkZdInfoOutVO = new RkZdInfoOutVO();
                            rkZdInfoOutVO.setZdName(inpatientDiagnosisPOS.get(0).getDiagnosisContent());
                            rkZdInfoOutVO.setId(inpatientDiagnosisPOS.get(0).getId());
                            rkZdInfoOutVOList.add(rkZdInfoOutVO);
                        } else {

                            List<BInpatientDiagnosis> inpatientDiagnosisPOS130 =diagnosisMap130.get(hospitalNumber);
                            if (CollectionUtil.isNotEmpty(inpatientDiagnosisPOS130)) {
                                RkZdInfoOutVO rkZdInfoOutVO = new RkZdInfoOutVO();
                                rkZdInfoOutVO.setZdName(inpatientDiagnosisPOS130.get(0).getDiagnosisContent());
                                rkZdInfoOutVO.setId(inpatientDiagnosisPOS130.get(0).getId());
                                rkZdInfoOutVOList.add(rkZdInfoOutVO);
                            }
                        }
                    } else {
                        RkZdInfoOutVO rkZdInfoOutVO = new RkZdInfoOutVO();
                        rkZdInfoOutVO.setZdName(select.getDiagnosisContent());
                        rkZdInfoOutVO.setId(select.getId());
                        rkZdInfoOutVOList.add(rkZdInfoOutVO);
                    }
                    patientInfoOutVO.setRkZdInfoList(rkZdInfoOutVOList);
                    if (null != patientInfoOutVO.getRkZdList()) {
                        patientInfoOutVO.setRkZdList(new ArrayList<>());
                    }
                }



                BHl7Yz yz = new BHl7Yz();
                List<BHl7Yz> yzList = yxHl7YzPOListll.stream().filter(e -> e.getPatientIdent().equals(patientIdent)).collect(Collectors.toList());
                if (null != yzList && yzList.size() > 0) {
                    yz = yzList.get(0);
                }
                //设置医嘱类型为饮食的 医嘱名称
                if (null != yz) {
                    patientInfoOutVO.setFood(yz.getOrderName());
                }

                PatientBindInputVO patientBindInputVO=new PatientBindInputVO();
                patientBindInputVO.setHospitalNumber(hospitalNumber);
                patientBindInputVO.setPatientIdent(patientIdent);

                List<PatientBindOutputVO> patientBindOutputVO = bindService.queryPatientBindHome(patientBindInputVO);
                patientInfoOutVO.setPatientBindOutputVO(patientBindOutputVO);

            });

        }

        return patientInfoList;
    }

    @Override
    public int countOfAllIcuPatient(String startTime, String endTime) {
        LambdaQueryWrapper<BHl7RkDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(BHl7RkDetail::getPatientIdent)
                .between(BHl7RkDetail::getRkTime, startTime, endTime)
                .groupBy(BHl7RkDetail::getPatientIdent);

        List<BHl7RkDetail> resultList = bHl7RkDetailMapper.selectList(wrapper);
        // 计算符合条件的分组记录数量
        int count = resultList.size();
        return count;
    }

    @Override
    public List<FuerInpatientInfoResult> getHomePatients(List<FuerInpatientInfoResult> list) {
        for (int i = 0; i < list.size(); i++) {
            FuerInpatientInfoResult fuerInpatientInfoResult=list.get(i);
            PatientBindInputVO patientBindInputVO=new PatientBindInputVO();
            patientBindInputVO.setHospitalNumber(fuerInpatientInfoResult.getInpatientId());
            patientBindInputVO.setPatientIdent(fuerInpatientInfoResult.getPatientId());

            List<PatientBindOutputVO> patientBindOutputVO = bindService.queryPatientBindHome(patientBindInputVO);
            fuerInpatientInfoResult.setPatientBindOutputVO(patientBindOutputVO);
        }

        return list;
    }


    @Override
    public BPatientResultVO selectOneByQuery(String hospitalNumber) {
        BPatient bPatient=bPatientMapper.selectOneByHospitalNumber(hospitalNumber);
        BPatientResultVO bPatientResultVO= BeanUtil.copyProperties(bPatient,BPatientResultVO.class);


        return bPatientResultVO;
    }

    @Override
    public FuerInpatientInfoResult getPatientInfo(String hospitalNumber,List<FuerInpatientInfoResult> list) {


        // 获取患者的绑定设备数据
        list = getHomePatients(list);

        // 过滤出符合 hospitalNumber 的单个患者数据
        List<FuerInpatientInfoResult> filteredList = list.stream()
                .filter(patient -> hospitalNumber.equals(patient.getInpatientId()))
                .collect(Collectors.toList());

        if (filteredList.isEmpty()) {
            throw new RuntimeException("未找到匹配的患者信息");
        }
        if (filteredList.size() > 1) {
            throw new RuntimeException("找到多个匹配的患者信息，请检查数据");
        }

        return filteredList.get(0);
    }
}


